<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 编辑区调整为16列 -->
      <el-col :span="16">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="新闻标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入新闻标题" />
          </el-form-item>

          <el-form-item label="作者" prop="author">
            <el-input v-model="form.author" placeholder="请输入作者姓名" />
          </el-form-item>

          <el-form-item label="新闻分类" prop="category">
            <el-select v-model="form.categoryId" placeholder="请选择分类">
              <el-option
                v-for="item in categoryOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="内容摘要" prop="summary">
            <el-input
              v-model="form.summary"
              type="textarea"
              :rows="3"
              placeholder="请输入内容摘要"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <!-- 富文本编辑器 -->
          <el-form-item label="新闻内容" prop="content">
            <div class="editor-container">
              <QuillEditor 
                ref="myQuillEditor"
                v-model:content="form.content" 
                contentType="html"
                :options="editorOptions"
                class="editor-content"
                @blur="onEditorBlur"
              />
            </div>
          </el-form-item>

          <!-- 优化图片上传组件 -->
          <el-form-item label="封面图片">
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleUploadChange"
              :on-remove="handleRemoveFile"
              :limit="1"
              accept="image/*"
            >
              <el-icon><Plus /></el-icon>
              <template #file="{ file }">
                <div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <el-icon><zoom-in /></el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>
            <el-dialog v-model="dialogVisible" width="60%">
              <img w-full :src="previewImageUrl" alt="预览" />
            </el-dialog>
          </el-form-item>

          <el-form-item label="发布时间">
            <el-date-picker
              v-model="form.createDate"
              type="datetime"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio :label="2">草稿</el-radio>
              <el-radio :label="1">立即发布</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <!-- 预览区调整为8列 -->
      <el-col :span="8">
        <div class="preview-area">
          <h3 class="preview-title">预览效果</h3>
          <div class="preview-content">
            <h2>{{ form.title || '新闻标题' }}</h2>
            <div class="meta-info">
              <span v-if="form.author" class="author">作者：{{ form.author }}</span>
              <span v-if="form.publishTime" class="publish-time">{{ form.publishTime }}</span>
            </div>
            <div class="summary" v-if="form.summary">{{ form.summary }}</div>
            <div v-html="form.content" class="ql-editor" />
            <img 
              v-if="coverPreview" 
              :src="coverPreview" 
              class="cover-preview"
              alt="封面预览"
            />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios'
// 使用兼容Vue3的富文本编辑器
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import {ElMessage} from "element-plus";
import {ref} from "vue";

export default {
  components: {
    QuillEditor
  },
  data(){
    return{
      //表单数据
      form: {
        id: null,
        title: '',
        author: '',
        categoryId: '',
        summary: '',
        content: '<h2>新闻内容标题</h2><p>在此处编辑您的新闻内容...</p>',
        picPath: '',
        modifyDate: '',
        status: null
      },
      // 新闻分类
      categoryOptions:null,
      //表单验证
      rules: {
        title: [{required: true, message: '请输入新闻标题', trigger: 'blur'}],
        author: [{required: true, message: '请输入作者姓名', trigger: 'blur'}],
        categoryId: [{required: true, message: '请选择新闻分类', trigger: 'change'}],
        content: [{
          validator: (rule, value, callback) => {
            // 检查内容是否只有空白字符
            const strippedValue = value.replace(/(<([^>]+)>)/gi, '').trim();
            if (!strippedValue) {
              callback(new Error('请输入新闻内容'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }]
      },
      // 富文本编辑器
      editorOptions:{
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            ['link', 'image', 'video'],
            ['clean']
          ]
        },
        placeholder: '请输入新闻内容...',
        theme: 'snow'
      },
      // 封面预览
      coverPreview :null,
      previewImageUrl:null,
      dialogVisible:false

    }
  },
  methods: {
    // 新闻分类
    category() {
      axios.get("http://localhost:8080/cate/category"
      ).then((resp) => {
        this.categoryOptions = resp.data.data
        console.log(this.categoryOptions)
      })
    },
    // 图片上传处理
    handleUploadChange(uploadFile){
      if (uploadFile.raw) {
        // 创建预览URL
        this.coverPreview = URL.createObjectURL(uploadFile.raw);
        this.previewImageUrl = this.coverPreview.value;
        // 实际项目中这里应该上传到服务器
        this.form.picPath = uploadFile.name;
      }
    },
    // 图片预览
    handlePictureCardPreview(file){
      this.previewImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 移除图片
    handleRemoveFile(){
      this.coverPreview = '';
      this.form.picPath = '';
    },
    // 编辑器失焦事件
    onEditorBlur(){
      // 触发内容验证
      this.$refs.formRef .validateField('content');
    },
    // // 生成唯一文件名
    // generateUniqueFileName(file){
    //   // const timestamp = new Date().getTime();
    //   const randomString = Math.random().toString(36).substring(2, 10);
    //   const extension = file.name.split('.').pop();
    //   // return `image_${timestamp}_${randomString}.${extension}`;
    //   return `image_${randomString}.${extension}`;
    // },
    // 提交表单（整体验证）
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          console.log('表单验证通过', this.form)
          // 提交到API...
          axios.post("http://localhost:8080/news/add",this.form).then(response =>{
            if (response.data.code === 200) {
              ElMessage.success('新闻添加成功');
              this.$router.push('/apinews/list');
            } else {
              ElMessage.error(`添加失败: ${response.data.message}`);
            }
          }).catch(error => {
            ElMessage.error(`请求失败: ${error.message}`);
          });
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    },
    // 重置表单
    resetForm(){
      this.$refs.formRef.resetFields()
    },
  },
  created(){
    this.category()
  },
}
</script>


<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.editor-container {
  position: relative;
}

.editor-content {
  height: 400px;
  margin-bottom: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.ql-toolbar) {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

:deep(.ql-container) {
  height: 350px;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}

.preview-area {
  margin-top: 40px;
  background: #fff;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.preview-title {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  color: #409eff;
  text-align: center;
  font-size: 18px;
}

.preview-content {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.preview-content h2 {
  color: #303133;
  margin-bottom: 15px;
  font-size: 22px;
}

.cover-preview {
  width: 100%;
  margin-top: 20px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.ql-editor {
  min-height: 300px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background: #fff;
}

.meta-info {
  margin: 20px 0;
  color: #606266;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}

.summary {
  color: #606266;
  font-size: 15px;
  line-height: 1.8;
  margin: 20px 0;
  padding: 15px;
  background-color: #f0f7ff;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  text-align: center;
}
</style>